// 使用InjectRepository装饰器并引入Repository即可使用typeorm的操作
import { Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './user.entity';

import { Like, Repository } from 'typeorm';
import { Tags } from './tags.entity';

@Injectable()
export class UserService {
   constructor(
    @InjectRepository(User)private readonly usersRepository: Repository<User>,
   @InjectRepository(Tags)private readonly tagsRepository: Repository<Tags>) { }
   /**
    * 
    * @param createUserDto 入参
    * @returns  创建用户
    */
   create(createUserDto: CreateUserDto) {
    const data = new User()
    data.name = createUserDto.name
    data.age = createUserDto.age
    return this.usersRepository.save(data)

  }
  /**
   * 
   * @param query  查询参数
   * @returns  查询用户
   */
   async findAll(query:{keyWord: string, page: number, pageSize: number }) {
    const data =  await this.usersRepository.find({
      //查询的时候如果需要联合查询需要增加 relations
      relations:['tags'],

      where: {
        name: Like(`%${query.keyWord}%`)
      },
      order: {
        id: "DESC"
      },
      skip: (query.page - 1)* query.pageSize,
      take: query.pageSize,
    })
    const total = await this.usersRepository.count({
      where: {
        name: Like(`%${query.keyWord}%`)
      },
    })

    return {
      data,
      total
    }
  }

  /**
   * 
   * @param id 用户id
   * @param updateUserDto  入参
   * @returns   更新用户信息
   */
  update(id: number, updateUserDto: UpdateUserDto) {
    return this.usersRepository.update(id, updateUserDto)
  }
/**
 * 
 * @param id 用户id
 * @returns  删除用户
 */

  remove(id: number) {
    return this.usersRepository.delete(id)
  }

  async addTags(params:{tags: string[], userId: number}){
    // 根据id 找到当前用户信息
    const userInfo = await this.usersRepository.findOne({where:{ id: params.userId}})
    
    const tagList:Tags[] = []
    // 通过循环，将tags 存入数据库
    for (let i = 0; i < params.tags.length; i++) {
      const T = new Tags()
      T.tags = params.tags[i]
      await this.tagsRepository.save(T)
      tagList.push(T)
    }
    // 更新当前用户的tags
    userInfo.tags = tagList
    // 将当前用户更新的值，存入到数据库
    return await this.usersRepository.save(userInfo) 
  }  
}
